<?php
namespace App\Repositories\GameServer;

use App\Models\GameServer\Order;
use App\Models\GameServer\Goods;
use App\Models\GameServer\UserInfo;
use App\Library\Custom\Util;

/**
* 订单表
*/
class OrderRepository
{
    /**
     * 创建订单
     * @param  int $goods_id 商品ID
     * @param  int $gamer_id 玩家ID
     * @return [type]           [description]
     */
    public function recharge($goods_id, $gamer_id)
    {
        $goods = Goods::findOrFail($goods_id);
        $gamer = UserInfo::findOrFail($gamer_id);

        $order_no = Util::orderNumber();
        $ip = Util::getIP();
        $ip_loc = Util::getCityTaobao($ip);

        $order = Order::create([
            'order_no' => $order_no,
            'goods_id' => $goods->id,
            'goods_name' => (string)$goods->item_name,
            'goods_price' => $goods->price,
            'product_no' => $goods->product_no,
            'quantity' => 1,
            'total' => $goods->price,
            'gamer_id' => $gamer->id,
            'gamer_name' => (string)$gamer->nickname,
            'expire_time' => 1500,//25分钟
            'status' => 0,
            'ip' => $ip,
            'ip_loc' => $ip_loc
        ]);

        return $order;

    }

    //通过玩家和商品id检测订单
    public function getOrderByGamerId($goods_id, $gamer_id)
    {
        $where['goods_id'] = $goods_id;
        $where['gamer_id'] = $gamer_id;
        $where['status'] = 0;

        $order = Order::where($where)->orderBy('created_at', 'desc')->first();

        return $order;
    }

    public function setTransid(Order $order, $transid)
    {
        $order->transid = $transid;
        $order->save();
    }

    public function deleteOrder($id)
    {
        return Order::destroy($id);
    }

    public function updateOrder($order_no, $data)
    {
        return Order::where('order_no', $order_no)->update($data);
    }

    public function getOrder($order_no)
    {
        return Order::where('order_no', $order_no)->first();
    }

    public function getOrders($where = [])
    {
        return Order::where($where)->orderBy('id', 'desc')->get();
    }
}